<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网页读取本地文件夹内容</title>
</head>
<body>
    <button class="btn">选择文件夹</button>
</body>
<script>
    let btn = document.querySelector('.btn')
    console.log(btn);
    btn.onclick = async function(){
        try{
            const handle = await showDirectoryPicker()    // 选择文件夹, 返回的句柄
            const root = await processHandle(handle)
            console.log(root);
            //==读取文件, 随便读取一个文件=====
            let f = root.children.filter(m => m.kind === 'file')[0]
            console.log(f);
            let file = await f.getFile()    //获得一个文件
            const reader = new FileReader() //要读取这个文件,需要用FileReader
            reader.readAsText(file, 'utf-8')
            reader.onload = e => {
                console.log( e.target.result );
            }
        }catch{
            //弹框点击取消时处理
        }
    }

    async function processHandle(handle){
        if(handle.kind === 'file'){ //如果是文件,就不用处理了
            return handle
        }
        handle.children = []
        const iter = handle.entries()  //文件夹句柄.entries, 返回一个异步迭代器, 
        for await(const item of iter){  //遍历这个文件夹内的所有文件或夹
            //item[0]文件名称, item[1]句柄
            handle.children.push(await processHandle(item[1]))
        }
        return handle
    }
</script>
</html>